import { defineConfig, loadEnv } from 'vite';
import path from 'path';
import createVitePlugins from './vite/plugins';

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_APP_HOST, VITE_APP_BASE_API } = env;
  return {
    define: {
      'process.env': env,
    },
    base: '/',
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src'),
        'xml-js': '@netless/xml-js',
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    // vite 相关配置
    server: {
      port: 8098,
      host: true,
      open: true,
      // proxy: {
      //   [VITE_APP_BASE_API]: {
      //     target: `${VITE_APP_HOST}${VITE_APP_BASE_API}`,
      //     changeOrigin: true,
      //     rewrite: p => p.replace(new RegExp(`^/`), ''),
      //   },
      // },
    },
    externals: {
      './cptable': 'var cptable',
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: atRule => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
      preprocessorOptions: {
        scss: {
          additionalData: `@import '@/assets/styles/variable.scss';`,
        },
      },
    },
  };
});
